import { h, resolveComponent } from 'vue'
import { isNil, find, cloneDeep } from 'lodash-es'
import { getValue, format, openWindow } from '/@/utils/helper'
import { TYPE_PDF, TYPE_OFFICE, TYPE_IMAGE } from '/@/model/attachment'

import Open32Filled from '@vicons/fluent/Open32Filled'

function renderArray(arr = []) {
  const spaceProps = { size: 'small' }
  const tagProps = { size: 'small' }

  return h(resolveComponent('n-space'), spaceProps, {
    default: () => arr.map(item => h(resolveComponent('n-tag'), tagProps, {
      default: () => item
    }))
  })
}

function renderFilePreview(src, filename) {
  return h(resolveComponent('n-button'), {
    text: true,
    'icon-placement': 'right',
    onClick: () => {
      if (src.indexOf('/api/viewer') === 0) {
        openWindow(src)
      } else {
        openWindow(src, filename)
      }
    }
  }, {
    default: () => '打开预览窗口',
    icon: () => h(resolveComponent('n-icon'), {
      size: 18
    }, {
      default: Open32Filled.render
    })
  })
}

function normalizeColumns(rawColumns) {
  const columns = cloneDeep(rawColumns)
  const normalized = []

  for (let i = 0; i < columns.length; i += 1) {
    const column = columns[i]

    if (column.key && column.title) {

      if (i === 0) {
        column.fixed = column.fixed || 'left'
      } else if (i === columns.length - 1) {
        column.fixed = column.fixed || 'right'
      }

      if (column.type === 'date') {
        column.width = 185
      }

      if (typeof column.render !== 'function') {
        column.render = function (row) {
          const value = getValue(row, column.key)

          if (isNil(value)) {
            return column?.nullValue
          }

          switch (column.type) {
            case 'date': {
              return format(value, column.format)
            }

            case 'file': {
              const ext = '.' + value.split('.').pop()

              if (TYPE_PDF.indexOf(ext) > -1) {
                return renderFilePreview(value, row?.ie_attachment?.filename)
              }

              if (TYPE_OFFICE.indexOf(ext) > -1) {
                // TODO
                if (row?.ie_attachment?.id) {
                  return renderFilePreview(`/api/viewer/${row?.ie_attachment?.id}`)
                }
              }

              if (TYPE_IMAGE.indexOf(ext) > -1) {
                return h(resolveComponent('n-image'), {
                  // use thumbor
                  src: '/unsafe/fit-in/140x140' + value,
                  previewSrc: value,
                  width: 140,
                  height: 140,
                  'object-fit': 'cover',
                  style: {
                    verticalAlign: 'top'
                  },
                  key: value
                })
              }

              // image from wx
              if (value.indexOf('https://thirdwx.qlogo.cn') === 0) {
                return h(resolveComponent('n-image'), {
                  // use thumbor
                  src: value,
                  previewSrc: value,
                  width: 140,
                  height: 140,
                  'object-fit': 'cover',
                  style: {
                    verticalAlign: 'top'
                  },
                  key: value
                })
              }

              break
            }

            case 'switch': {
              const boolValue = Boolean(value)

              return h(resolveComponent('n-switch'), {
                disabled: boolValue,
                value: boolValue
              })
            }

            case 'richtext': {
              const div = document.createElement('div')

              div.innerHTML = value

              // replace table to [表格]
              ;(div.querySelectorAll('table' || [])).forEach(el => {
                el.parentNode.replaceChild(document.createTextNode('[表格]'), el)
              })

              // replace image to [图片]
              ;(div.querySelectorAll('[data-mce-src]' || [])).forEach(el => {
                el.parentNode.replaceChild(document.createTextNode('[图片]'), el)
              })

              // replace katex to [公式]
              ;(div.querySelectorAll('[id*=katex_]' || [])).forEach(el => {
                el.parentNode.replaceChild(document.createTextNode('[公式]'), el)
              })

              return div.innerText
            }
          }

          if (
            Array.isArray(column.options) &&
            column.options.length
          ) {
            const {
              label,
              type
            } = find(column.options, ['value', value]) || {}

            if (label) {
              return h(resolveComponent('n-tag'), {
                type,
                size: 'small'
              }, {
                default: () => label
              })
            }
          }

          if (Array.isArray(value)) {
            return renderArray(value)
          }

          if (
            typeof value === 'string' &&
            column.maxLen !== undefined
          ) {
            return value.slice(0, column.maxLen)
          }

          return value
        }
      }

      column.align = column.align || 'center'

      normalized.push(column)
    }
  }

  return normalized
}

export default normalizeColumns
